<?php

namespace app\model;

use app\eslib\EsUtils;
use think\Model;
use think\facade\Cache;
use think\facade\Db;

class EcCategoryModel extends Model
{
    /**
     * 该表将与模型关联。
     * @var string
     */
    public $table = 'ec_category';

    // 开启自动时间戳（默认为整型int）
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     * 返回 状态数据 访问器的值
     * @return string
     */
    public function getStatusDataAttr(): array
    {
        $data = [
            ['text' => '正常', 'value' => 1],
            ['text' => '禁用', 'value' => 0],
        ];
        return $data;
    }

    /**
     * 返回 状态 访问器的值
     * @return string
     */
    public function getStatusTextAttr()
    {
        $value = $this->getData('status');
        if (is_numeric($value)) {
            $value = intval($value);
        }
        $data = (array) $this->getStatusDataAttr();
        $result = array_filter($data, function ($v) use ($value) {
            return $v['value'] == $value;
        }, ARRAY_FILTER_USE_BOTH);
        return $result ? current($result)['text'] : $value;
    }

    /**
     * 获取PID
     */
    public static function getPid($id, $deepth = 0, $_level = 0)
    {
        $cacheKey = "ec_category_pid_{$id}_{$deepth}";
        if ($_level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $pid = Db::table((new static())->table)->where('id', $id)->value('pid');
        if ($pid == 0 || $_level == $deepth) {
            $data = $pid;
        } else {
            $data = self::getPid($pid, $deepth, $_level + 1);
        }
        if ($_level == 0) {
            Cache::set($cacheKey, $pid);
            ModelUtils::cachePut('ec_category', $cacheKey);
        }
        return $data;
    }

    /**
     * [弃用] 返回多维树形数据
     */
    public static function getTreeList($pid = 0)
    {
        $list = self::where('pid', $pid)->select();
        $data = [];
        foreach ($list as $row) {
            $row['children'] = self::getTreeList($row['id']);
            $data[] = $row;
        }
        return $data;
    }
    /**
     * 返回带前缀的一维树形数据
     */
    public static function getTreeRows($pid = 0, $level = 0)
    {
        $cacheKey = 'ec_category_tree_rows_' . $pid;
        if ($level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $list = self::where('pid', $pid)->order('id')->select();
        $data = [];
        foreach ($list as $row) {
            $row->_prefix = str_repeat('|----', $level);
            $row->_level = $level;
            $data[] = $row;
            $listTemp = self::getTreeRows($row['id'], $level + 1);
            if ($listTemp) {
                $data = array_merge($data, $listTemp);
            }
        }
        unset($list);
        if ($level == 0) {
            Cache::set($cacheKey, $data, 10);
        }
        return $data;
    }
    /**
     * 返回包含KV结构的一维树形数据
     */
    public static function getDictData($pid = 0, $level = 0)
    {
        $cacheKey = 'ec_category_dict_data_' . $pid;
        if ($level == 0) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return $data;
            }
        }
        $list = Db::table((new static())->table)->where('pid', $pid)->order('id')->select()->toArray();
        $data = [];
        $rowTemp = [];
        foreach ($list as $row) {
            $rowTemp = ['text' => str_repeat('|----', $level) . $row['category_name'], 'value' => $row['id'], '_level' => $level];
            $data[] = $rowTemp;
            $listTemp = self::getDictData($row['id'], $level + 1);
            if ($listTemp) {
                $data = array_merge($data, $listTemp);
            }
        }
        unset($list);
        if ($level == 0) {
            array_unshift($data, ['text' => '请选择分类', 'value' => 0, '_level' => $level]);
            Cache::set($cacheKey, $data);
            ModelUtils::cachePut('ec_category', $cacheKey);
        }
        return $data;
    }

    public static function getListData($page, $pageSize, $searchText)
    {
        $cacheKey = EsUtils::shortMD5('auth_rule_' . $page . '_' . $pageSize . '-' . $searchText);
        $data = Cache::get($cacheKey);
        if ($data) {
            return $data;
        }
        if ($searchText) {
            $data = EcCategoryModel::where('id', intval($searchText))->whereOr('category_name', 'like', "%{$searchText}%")->paginate($pageSize);
        } else {
            $data = EcCategoryModel::getTreeRows();
            $data = ['total' => count($data), 'data' => EsUtils::arrayPaginate($data, $page, $pageSize)];
        }
        Cache::set($cacheKey, $data, 10);
        ModelUtils::cachePut('ec_category', $cacheKey);
        return $data;
    }

    /**
     * 复制记录
     */
    public static function copy($id)
    {
        $data = self::find($id)->toArray();
        $data['category_name'] .= ' - 副本';
        unset($data['id']);
        unset($data['created_at']);
        unset($data['updated_at']);
        self::create($data);
        return 1;
    }
}
